package com.work.formaldehyde.lunch;

import android.Manifest;
import android.app.ActivityOptions;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.umeng.analytics.MobclickAgent;
import com.work.formaldehyde.MainActivity;
import com.work.formaldehyde.R;
import com.work.formaldehyde.activity.LoginActivity;
import com.work.formaldehyde.activity.YinSiActivity;
import com.work.formaldehyde.activity.YongHuXieYiActivity;
import com.work.formaldehyde.util.ApiUtils;
import com.work.formaldehyde.util.Url;

import java.util.List;

public class LunchActivity extends AppCompatActivity implements View.OnClickListener {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_lunch);
        inti();
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    private boolean login_ = true;
    private TextView two, four, nit, shi;

    /**
     * 初始化加载调用方法
     */
    public void inti() {
//        judgePermission();
        if (Url.QIDONGNUM.equals("")) {
            LayoutInflater inflater = LayoutInflater.from(this);
            View layout = inflater.inflate(R.layout.popupwindow_yinsiquanxian, null);
            two = layout.findViewById(R.id.two);
            two.setOnClickListener(this);
            four = layout.findViewById(R.id.four);
            four.setOnClickListener(this);
            nit = layout.findViewById(R.id.nit);
            nit.setOnClickListener(this);
            shi = layout.findViewById(R.id.shi);
            shi.setOnClickListener(this);
            new AlertDialog.Builder(this)
                    .setTitle("用户协议和隐私政策")
                    .setView(layout)
                    .setPositiveButton("是", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (login_) {
                                Intent intent = new Intent(LunchActivity.this, MainActivity.class);
                                startActivity(intent);
                                LunchActivity.this.finish();
                            }
                        }
                    })
                    .setNegativeButton("否", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            onBackPressed();
                        }
                    })
                    .show();
        } else
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    if (login_) {
                        Intent intent = new Intent(LunchActivity.this, MainActivity.class);
                        startActivity(intent);
                        LunchActivity.this.finish();
                    }
                }
            }, 3000);
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        List<String> providers = locationManager.getProviders(true);
        Criteria criteria = new Criteria();
        criteria.setAltitudeRequired(true);//设置是否可以定位海拔,如果设置定位海拔，返回一定是gps
        String bestProvider = locationManager.getBestProvider(criteria, false);
        myLocationListener = new MyLocationListener();
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    Activity#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for Activity#requestPermissions for more details.
            return;
        }
        locationManager.requestLocationUpdates("network", 0, 0, myLocationListener);
    }

    /**
     * 全透状态栏
     */
    public void setStatusBarFullTransparent() {
        if (Build.VERSION.SDK_INT >= 21) {//21表示5.0
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= 19) {//19表示4.4
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //虚拟键盘也透明
            //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }

    protected void judgePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查该权限是否已经获取
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
//
//            // sd卡权限
//            String[] SdCardPermission = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
//            if (ContextCompat.checkSelfPermission(this, SdCardPermission[0]) != PackageManager.PERMISSION_GRANTED) {
//                // 如果没有授予该权限，就去提示用户请求
//                ActivityCompat.requestPermissions(this, SdCardPermission, 100);
//            }
//
//            //手机状态权限
//            String[] readPhoneStatePermission = {Manifest.permission.READ_PHONE_STATE};
//            if (ContextCompat.checkSelfPermission(this, readPhoneStatePermission[0]) != PackageManager.PERMISSION_GRANTED) {
//                // 如果没有授予该权限，就去提示用户请求
//                ActivityCompat.requestPermissions(this, readPhoneStatePermission, 200);
//            }

            //定位权限
            String[] locationPermission = {Manifest.permission.ACCESS_FINE_LOCATION};
            if (ContextCompat.checkSelfPermission(this, locationPermission[0]) != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                ActivityCompat.requestPermissions(this, locationPermission, 300);
            }
//
//            String[] ACCESS_COARSE_LOCATION = {Manifest.permission.ACCESS_COARSE_LOCATION};
//            if (ContextCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION[0]) != PackageManager.PERMISSION_GRANTED) {
//                // 如果没有授予该权限，就去提示用户请求
//                ActivityCompat.requestPermissions(this, ACCESS_COARSE_LOCATION, 400);
//            }
//
//
//            String[] READ_EXTERNAL_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE};
//            if (ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE[0]) != PackageManager.PERMISSION_GRANTED) {
//                // 如果没有授予该权限，就去提示用户请求
//                ActivityCompat.requestPermissions(this, READ_EXTERNAL_STORAGE, 500);
//            }
//
//            String[] WRITE_EXTERNAL_STORAGE = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
//            if (ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE[0]) != PackageManager.PERMISSION_GRANTED) {
//                // 如果没有授予该权限，就去提示用户请求
//                ActivityCompat.requestPermissions(this, WRITE_EXTERNAL_STORAGE, 600);
//            }

        } else {
        }
    }


    public View contentViewGroup;

    public void setFitSystemWindow(boolean fitSystemWindow) {
        if (contentViewGroup == null) {
            contentViewGroup = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
        }
        contentViewGroup.setFitsSystemWindows(fitSystemWindow);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            login_ = false;
// 显示状态栏
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            LunchActivity.this.finish();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    public static LocationManager locationManager;
    public static MyLocationListener myLocationListener;
    public static String latLongString;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.two:
                Intent yhxy = new Intent(LunchActivity.this, YongHuXieYiActivity.class);
                startActivity(yhxy, ActivityOptions.makeSceneTransitionAnimation(LunchActivity.this).toBundle());
                break;
            case R.id.four:
                Intent yszc = new Intent(LunchActivity.this, YinSiActivity.class);
                startActivity(yszc, ActivityOptions.makeSceneTransitionAnimation(LunchActivity.this).toBundle());
                break;
            case R.id.nit:
                Intent yhxy1 = new Intent(LunchActivity.this, YongHuXieYiActivity.class);
                startActivity(yhxy1, ActivityOptions.makeSceneTransitionAnimation(LunchActivity.this).toBundle());
                break;
            case R.id.shi:
                Intent yszc1 = new Intent(LunchActivity.this, YinSiActivity.class);
                startActivity(yszc1, ActivityOptions.makeSceneTransitionAnimation(LunchActivity.this).toBundle());
                break;
        }
    }

    public class MyLocationListener implements LocationListener {

        //当定位位置改变的调用的方法
        //Location : 当前的位置
        @Override
        public void onLocationChanged(Location location) {
            float accuracy = location.getAccuracy();//获取精确位置
            double altitude = location.getAltitude();//获取海拔
            final double latitude = location.getLatitude();//获取纬度，平行
            final double longitude = location.getLongitude();//获取经度，垂直
            new Thread(new Runnable() {
                @Override
                public void run() {
                    List<Address> addsList = null;
                    Geocoder geocoder = new Geocoder(LunchActivity.this);
                    try {
                        addsList = geocoder.getFromLocation(latitude, longitude, 10);//得到的位置可能有多个当前只取其中一个
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (addsList != null && addsList.size() > 0) {
                        for (int i = 0; i < addsList.size(); i++) {
                            final Address ads = addsList.get(i);
                            latLongString = ads.getLocality();//拿到城市
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
//                                    locationChange.setText(latLongString + ads.getAddressLine(0) + ads.getAddressLine(1));
                                    Url.ADDRESSCITY = latLongString;
                                    Url.ADDRESSCITYS = ads.getAddressLine(0);
                                    ApiUtils.SetLog("city="+Url.ADDRESSCITY +",citys="+ Url.ADDRESSCITYS);
                                }
                            });
                        }
                    }
                }
            }).start();
        }

        //当定位状态发生改变的时候调用的方式
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub

        }

        //当定位可用的时候调用的方法
        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }

        //当定位不可用的时候调用的方法
        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        locationManager.removeUpdates(myLocationListener);//关闭gps,但是高版本中规定打开和关闭gps必须由用户自己主观的去实现，代码已经不允许进行操作
    }

}
